<?php
namespace app\api\controller;
use think\Controller;
use think\Db;

class  Weixinfws extends Base  {
    private $config=array(
        'APPID'              => 'wxcb63bdccb205e77b',
        'MCHID'              => '1603436544',
        'KEY'                => 'ykIaqVCiOW44kcYfIi6VxflcNlaDKCG5',
        'APPSECRET'          => '93121d5eba0d227aec238cfcd8ae7835',
        'NOTIFY_URL'         => 'http://csdl.jintianjifen.cn/api/Weixin/huidiao',
 
    );
    public $body;
    public $total_fee;
    public $out_trade_no;

    public function __construct($config=null){
        if (!empty($config)) {
            $this->config=$config;
        }
    }
    protected function apiError($code, $msg = '')
    {
        if (!$msg) {
            $info['msg'] = $this->_error[$code]['msg'];
        } else {
            $info['msg'] = $msg;
        }
        $info['status'] = $code;
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
        exit();
    }
    public function ttttt()
{
//    $path ='15905689923,15375050646,15178459467,17355087393,13637043001,18296418851,15255071176,18907721264,18205549888,18755075555,13516400600';
        $map = [];
        $map['record_shop_id'] = 6;
        $map['record_status'] = 2;
//        $map['record_fws'] = 1;
        $a = Db::name('record')
            ->where($map)
            ->where('record_add_time','>=','2021-11-06 00:00:00')
            ->select();
        $getget3 = Db::name('order')
            ->where('o_shop_id',6)
            ->where('o_type','in','1,2')
            ->where('o_status','in','2,3,4,5')
            ->where('o_add_time','>=','2021-11-06 00:00:00')
//            ->field('o_id,o_jifen,o_jifen,o_money')
            ->select();

dump($getget3);
die;
    $weixinpay_config=$this->config;
    $order = [];
    $config=array(
        'appid'=>$weixinpay_config['APPID'],
        'mch_id'=>$weixinpay_config['MCHID'],
        'nonce_str'=>'test',
        'spbill_create_ip'=>$_SERVER['REMOTE_ADDR'],
        'notify_url'=>$weixinpay_config['NOTIFY_URL']
    );
    $config = [
        "business_code" => "1900013511_10000",
        "contact_info" => [
            "contact_name" => "pVd1HJ6zyvPedmty7/mYNxLMpyOb+tI0pQO/0kjiwfqdfg==", //管理员姓名
            "contact_id_number" => "pVd1HJ6zyvPedzGaV+X5Kz4jBHLiCyObapQO/0kjiwfqdfg==", //管理员身份证号
            "mobile_phone" => "pVd1HJ6zyv1z0NVa8MRtelw/wDa4SzfeespQO/0kjiwfqdfg==",  //管理员电话
            "contact_email" => "pVd1HJ6I0m+Jv1z0NVa8MRtelw/wDa4SzfeespQO/0kjiwfqdfg=="  //管理员邮箱
        ],
        "subject_info" => [
            "subject_type" => "SUBJECT_TYPE_ENTERPRISE",
            "business_license_info" => [
                "license_copy" => "47ZC6GC-cuxi-v-4KGprrKhwFNIO4kqg05InE4d2I6_H7I4",  //营业执照
                "license_number" => "123456789012345678",  //信用代码
                "merchant_name" => "腾讯科技有限公司",  //商户名称
                "legal_person" => "张三"  //法人
            ],
            "identity_info" => [ //法人信息
                "id_doc_type" => "IDENTIFICATION_TYPE_IDCARD",
                "id_card_info" => [
                    "id_card_copy" => "jTpGmxUX3FBWVQ5NJTZvlD8daLC-ehEuo0BJqRTvDujqhThn4ReFxikqJ5YW6zFQ",//身份证人像面
                    "id_card_national" => "47ZC6GC-vnrbEny_Ie_An5-tCpqxuUv0OF4wFNIO4kqg05InE4d2I6_H7I4",//身份证国徽面
                    "id_card_name" => "pVd1HJ6zyvPedzGaV+X3qtmrq9bb9t/wDa4SzfeespQO/0kjiwfqdfg==",
                    "id_card_number" => "AOZdYGISxo4y44/UgZ69bdu9X+tq79Jtt7+I8juwEc4P4TG5xzchG/5IL9DBd+Z0zZXkw==",
                    "card_period_begin" => "2026-06-06",
                    "card_period_end" => "2026-06-06"
                ],
                "owner" => true
            ],
        ],
        "business_info" => [
            "merchant_shortname" => "张三餐饮店", //商户简称
            "service_phone" => "0758XXXXX", //商户客服电话
            "sales_info" => [
                "sales_scenes_type" => [
                    "SALES_SCENES_MP"
                ],
                "mp_info" => [
                    "mp_appid" => "wx1234567890123456",
                    "mp_pics" => [
                        "ZC6GC-vnrbEny_Ie_An5-tCpqxucuxi-vByf3Gjm7KE53JXvGy9tqZm2XAUf-4KGprrKhpVBD"
                    ]
                ]
            ]
        ],
        "settlement_info" => [
            "settlement_id" => "719",
            "qualification_type" => "餐饮"
        ],
        "bank_account_info" => [
            "bank_account_type" => "BANK_ACCOUNT_TYPE_CORPORATE",
            "account_name" => "AOZdYGISxo4y44/UgZ69bdu9X+tfMUJ9dl+L79Jtt7+I8juwEc4P4TG5xzchG/5IL9DBd+Z0zZXkw==",
            "account_bank" => "工商银行",
            "bank_address_code" => "110000",
            "bank_name" => "施秉县农村信用合作联社城关信用社",
            "account_number" => "d+xT+MQCvrLHUVDWv/8MR/dB7TkXM2hcR3WL8sPndjXTd75kPkyjqnoMRrEEaYQE8ZRGYoeorwC+w=="
        ],
    ];

//    $data=array_merge($order,$config);
//    $data=array_merge($order,$config);
//    $sign=$this->makeSign($data);
//    $data['sign']=$sign;
    $xml=$this->arr2xml($config);
    $xml=json_encode($config);
//    dump($xml);die;
    $url = 'https://api.mch.weixin.qq.com/v3/applyment4sub/applyment/';
    $header = [
        "Content-type:application/json",
        "Accept:application/json",
        "User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
    ];
//    $header[] = "Accept: application/json";
//    $header[] = "User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
    $ch = curl_init ($url);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
    $response = curl_exec($ch);
    if(curl_errno($ch)){
        print curl_error($ch);
    }
    curl_close($ch);
    dump($response);die;
    $result=$this->toArray($response);
    dump($result);die;
    $result['sign']=$sign;
    $result['nonce_str']='test';
    $result2 = $this->getOrder($result['prepay_id']);
    return $result2;

}
    public function arr2xml($data, $root = true){
        $str="";
        if($root)$str .= "<xml>";
        foreach($data as $key => $val){
            if(is_array($val)){
                $child = $this->arr2xml($val, false);
                $str .= "<$key>$child</$key>";
            }else{
                $str.= "<$key><![CDATA[$val]]></$key>";
            }
        }
        if($root)$str .= "</xml>";
        return $str;
    }

    public function WeChatPayReady(){
        $order = [
            'attach'       => "QRcodePay",
            'body'         => "一元开店",
            'total_fee'    => 1 * 100,
            'out_trade_no' => 'T' . time(),
            'product_id'   => "",
            'trade_type'   => "JSAPI",
            'sub_mch_id'   => "1603445926",
            'openid'   => "oxIEc6P0qYWyjDjN92OCMvlc8ccI",
        ];
        $weixinpay_config=$this->config;
        $config=array(
            'appid'=>$weixinpay_config['APPID'],
            'mch_id'=>$weixinpay_config['MCHID'],
            'nonce_str'=>'test',
            'spbill_create_ip'=>$_SERVER['REMOTE_ADDR'],
            'notify_url'=>$weixinpay_config['NOTIFY_URL'],
            'profit_sharing'=>'Y'
        );
//        if(!empty($type)){
//            $config['notify_url']=$type;
//        }
        $data=array_merge($order,$config);
        $sign=$this->makeSign($data);
        $data['sign']=$sign;
        $xml=$this->toXml($data);
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $header[] = "Content-type: text/xml";
        $ch = curl_init ($url);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        $response = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }
        curl_close($ch);
        dump($response);die;
        $result=$this->toArray($response);
        $result['sign']=$sign;
        $result['nonce_str']='test';
        $result2 = $this->getOrder($result['prepay_id']);
        return $result2;
    }
    

    public function getDateBytimeDate($string){
        $replacement = '-';
        $replacement2 = ':';
        $a = substr_replace($string, $replacement, 4, 0);
        $b = substr_replace($a, $replacement, 7, 0);
        $c = substr_replace($b, ' ', 10, 0);
        $d = substr_replace($c, $replacement2, 13, 0);
        $e = substr_replace($d, $replacement2, 16, 0);
        return $e;
    }

    public function write_admin_log($data)
    {
        file_put_contents ( APP_PATH."api/controller/wxpay_user_log.txt", date ( "Y-m-d H:i:s" ) . "  " . $data . "\r\n", FILE_APPEND );
    }
    public function huidiao(){
//        $getInfo = [
//            'return_code' => 'SUCCESS' ,
//            'result_code' => 'SUCCESS' ,
//            'out_trade_no' => '2021061610251559258551' ,
//            'time_end' => '2021-06-16 22:42:59' , //不转义了
//            'attach' => 'payMoneyOne' ,
//            'transaction_id' => '400001202106161025155925855100001' ,
//            'total_fee' => '400001202106161025155925855100001' ,
//        ];
        $xml=file_get_contents('php://input');
        $getInfo=$this->toArray($xml);
        $this->write_admin_log("response: ".var_export($getInfo,true));
        $data_sign=$getInfo['sign'];
        unset($getInfo['sign']);
        $sign=$this->makeSign($getInfo);
        if ($sign===$data_sign && $getInfo['return_code']=='SUCCESS' && $getInfo['result_code']=='SUCCESS') {
            Db::startTrans ();
            try{
                $num = $getInfo['out_trade_no'];
                $time = $this->getDateBytimeDate("{$getInfo['time_end']}");
                if($getInfo['attach'] != 'payMoney'){
                    $info = Db::name('order')->where('o_order_num',$num)->find();
                }
                $red_rat = Db::name('jifen_conf')->where('conf_id',1)->value('conf_rate');
                $b = new Base();
                switch($getInfo['attach']){
                    case 'joinFund':
                        $fund_info = Db::name('fund')->where('fund_id',$info['o_fund_id'])->find();
                        Db::name('fund_join')->insert(['j_order_id'=>$info['o_id'],'j_fund_id'=>$info['o_fund_id'],'j_user_id'=>$info['o_user_id'],'j_pay'=>$info['o_money'],'j_pay_time'=>$time]);
                        Db::name('fund')->where(['fund_id'=>$info['o_fund_id']])->inc ('fund_join')->inc('fund_money',$info['o_money'])->update ();
                        if(($fund_info['fund_money']+$info['o_money']) >= $fund_info['fund_plan']){
                            Db::name('fund')->where('fund_id',$info['o_fund_id'])->setField ('fund_status',5);
                            Db::name('fund_join')->where('j_fund_id',$info['o_fund_id'])->setField ('j_status',2);
                        }
                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'参与众筹','n_content'=>'您参与众筹支付'.$info['o_money'].'元','n_images'=>'','n_type'=>3,'n_user_id'=>$info['o_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                        $b->jpushUser(1,$info['o_user_id'],'您参与众筹支付'.$info['o_money'].'元',json([]));
                        break;
                    case 'payOne':
                        Db::name('u_user')->where('user_id',$info['o_user_id'])->update (['user_one_pay'=>2,'user_edit_time'=>date('Y-m-d H:i:s')]);
                        break;
                    case 'payMoney':
                        $v = Db::name('order')->where(['o_order_num'=>['in',$num]])->field('SUM(o_money) AS o_money,SUM(o_jifen) AS o_jifen,o_user_id')->find();
                        $user = Db::name('u_user')->where('user_id',$v['o_user_id'])->find();
                        $rat = Db::name('jifen_conf')->where('conf_id',2)->value('conf_rate');
                        $nums = Db::name('order')->where(['o_order_num'=>['in',$num]])->select ();
                        foreach($nums as $key=>$vo){
                            $oi_goods_name = Db::name('order_info')->where('oi_order_id',$vo['o_id'])->column ('oi_goods_name');
                            if($vo['o_jifen'] > 0){
                                $b->consume ($vo['o_user_id'] , $vo['o_jifen'] , $vo['o_shop_id']);
                                Db::name('shop')->where('shop_id',$vo['o_shop_id'])->setInc ('shop_balance_yet',$vo['o_jifen']*$rat);
                                Db::name('jifen_consume')->insert(['consume_content'=>'购买'.implode (',',$oi_goods_name).'商品订单消费'.$vo[ 'o_jifen' ].'积分','consume_user_id'=>$user['user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                            }

                            if($vo['o_money'] > 0){
//                                $red_yajin_jian = $this->getRedYajinValue($vo['o_id'],$red_rat);
//                                if($red_yajin_jian > $vo['o_money']){
//                                    $red_yajin_jian = $vo['o_money'];
//                                }
                                Db::name('shop')->where('shop_id',$vo['o_shop_id'])->setInc ('shop_balance_yet',$vo['o_money']);
                            }
                            $o_status = in_array ($vo['o_cate'],[1,3]) ? 2 : 10;
                            Db::name('order')->where('o_order_num',$vo['o_order_num'])->update(['o_status'=>$o_status,'o_pay_status'=>2, 'o_third_order_num' => $getInfo[ 'transaction_id' ]]);
                            $dec = Db::name('order_info')->where('oi_order_id',$vo['o_id'])->find();
                            if($dec['oi_goods_model']){
                                Db::name('product_model')->where('m_id',$dec['oi_goods_model'])->setDec ('m_num',$dec['oi_num']);
                            }else{
                                Db::name('product')->where('p_id',$dec['oi_goods_id'])->setDec ('p_stock_num',$dec['oi_num']);
                            }
                            Db::name('product')->where('p_id',$dec['oi_goods_id'])->setInc ('p_sell_yet',$dec['oi_num']);

                            Db::name('notice')->insert (['n_to'=>2,'n_title'=>'订单消息','n_content'=>'您有新的订单！','n_images'=>'','n_type'=>2,'n_user_id'=>$vo['o_shop_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                            try{
                                $b->jpushShop(1,$vo['o_shop_id'],'您有新的订单！',['type2' => 1024,'msg' => "您有一个新的线上订单"]);
                            }catch (\Exception $e){}


                            Db::name('notice')->insert (['n_to'=>1,'n_title'=>'订单支付','n_content'=>'购买'.implode (',',$oi_goods_name).'商品订单支付成功，等待卖家处理','n_images'=>'','n_type'=>2,'n_user_id'=>$user['user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                            try{
                                $b->jpushUser(1,$user['user_id'],'订单支付成功，等待卖家处理',json([]));

                                $b->jpushDeviceShop($vo['o_shop_id'], '您有一个新的线上订单');
                            }catch (\Exception $e){}
                        }

                        break;
                    case 'payMoneyOne':
                        $user = Db::name('u_user')->where('user_id',$info['o_user_id'])->find();
                        // $rat = Db::name('jifen_conf')->where('conf_id',1)->value('conf_rate');
                        $oi_goods_name = Db::name('order_info')->where('oi_order_id',$info['o_id'])->value ('oi_goods_name');
                        if($info['o_money'] > 0){
//                            $red_yajin_jian = $this->getRedYajinValue($info['o_id'],$red_rat);
//                            if($red_yajin_jian > $info['o_money']){
//                                $red_yajin_jian = $info['o_money'];
//                            }
                            Db::name('shop')->where('shop_id',$info['o_shop_id'])->setInc ('shop_balance_yet',$info['o_money']-$info['o_m_money']);
                        }
                        $o_status = in_array ($info['o_cate'],[1,3]) ? 2 : 10;
                        Db::name('order')->where('o_order_num',$info['o_order_num'])->update(['o_status'=>$o_status,'o_pay_status'=>2, 'o_third_order_num' => $getInfo[ 'transaction_id' ]]);
                        $dec = Db::name('order_info')->where('oi_order_id',$info['o_id'])->find();
                        if($dec['oi_goods_model']){
                            //不是id......
//                            Db::name('product_model')->where('m_id',$dec['oi_goods_model'])->setDec ('m_num',$dec['oi_num']);
                        }else{
                            Db::name('product')->where('p_id',$dec['oi_goods_id'])->setDec ('p_stock_num',$dec['oi_num']);
                        }
                        Db::name('product')->where('p_id',$dec['oi_goods_id'])->setInc ('p_sell_yet',$dec['oi_num']);

                        //-----------------------------分佣 start -----------------------------------------
                        $one_good = Db::name('product')->where('p_id',$dec['oi_goods_id'])->find ();
                        $one_fen = [];
                        $one_fen[] = [
                            'record_order_number' => $info['o_order_num'],
                            'record_user_id' => $info['o_user_id'],
                            'record_from_type' => 1,
                            'record_payment_type' => $info['o_pay_type'],
                            'record_status' => 1,
//                            'record_get_type' => 2,
                            'record_jifen' => $one_good['p_give'],
                            'record_money' => 0,
                            'record_add_time' => date('Y-m-d H:i:s'),
                        ];
                        $one_fen[] = [
                            'record_order_number' => $info['o_order_num'],
                            'record_user_id' => 0,
                            'record_from_type' => 5,
                            'record_payment_type' => $info['o_pay_type'],
                            'record_status' => 1,
//                            'record_get_type' => 1,
                            'record_jifen' => 0,
                            'record_money' => $one_good['p_m_single_system'],
                            'record_add_time' => date('Y-m-d H:i:s'),
                        ];
                        if($info['o_m_user_id'] > 0){
                            $one_fen[] = [
                                'record_order_number' => $info['o_order_num'],
                                'record_user_id' => $info['o_m_user_id'],
                                'record_from_type' => 3,
                                'record_payment_type' => $info['o_pay_type'],
                                'record_status' => 1,
//                                    'record_get_type' => 1,
                                'record_jifen' => $one_good['p_m_single_one_jifen'],
                                'record_money' => $one_good['p_m_single_one_money'],
                                'record_add_time' => date('Y-m-d H:i:s'),
                            ];
                            if($user['user_recommend']){
                                $recommendLevel = Db::name('u_user')->where('user_id',$user['user_recommend'])->value('user_level');
                                if($recommendLevel && $recommendLevel > 1){
                                    $one_fen[] = [
                                        'record_order_number' => $info['o_order_num'],
                                        'record_user_id' => $user['user_recommend'],
                                        'record_from_type' => 4,
                                        'record_payment_type' => $info['o_pay_type'],
                                        'record_status' => 1,
//                                        'record_get_type' => 1,
                                        'record_jifen' => 0,
                                        'record_money' => $one_good['p_m_single_two'],
                                        'record_add_time' => date('Y-m-d H:i:s'),
                                    ];
                                }else{
                                    $one_fen[] = [
                                        'record_order_number' => $info['o_order_num'],
                                        'record_user_id' => 0,
                                        'record_from_type' => 6,
                                        'record_payment_type' => $info['o_pay_type'],
                                        'record_status' => 1,
//                                        'record_get_type' => 1,
                                        'record_jifen' => 0,
                                        'record_money' => $one_good['p_m_single_two'],
                                        'record_add_time' => date('Y-m-d H:i:s'),
                                    ];
                                }
                            }else{
                                $one_fen[] = [
                                    'record_order_number' => $info['o_order_num'],
                                    'record_user_id' => 0,
                                    'record_from_type' => 6,
                                    'record_payment_type' => $info['o_pay_type'],
                                    'record_status' => 1,
//                                    'record_get_type' => 1,
                                    'record_jifen' => 0,
                                    'record_money' => $one_good['p_m_single_two'],
                                    'record_add_time' => date('Y-m-d H:i:s'),
                                ];
                            }
                        }else{
                            $one_fen[] = [
                                'record_order_number' => $info['o_order_num'],
                                'record_user_id' => 0,
                                'record_from_type' => 6,
                                'record_payment_type' => $info['o_pay_type'],
                                'record_status' => 1,
//                                'record_get_type' => 1,
                                'record_jifen' => 0,
                                'record_money' => $one_good['p_m_single_all_money'] - $one_good['p_m_single_system'],
                                'record_add_time' => date('Y-m-d H:i:s'),
                            ];
                        }
                        Db::name('m_record')->insertAll($one_fen);
                        //-----------------------------分佣 end  ------------------------------------------

                        Db::name('notice')->insert (['n_to'=>2,'n_title'=>'订单消息','n_content'=>'您有新的订单！','n_images'=>'','n_type'=>2,'n_user_id'=>$info['o_shop_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                        try{
                            $b->jpushShop(1,$info['o_shop_id'],'您有新的订单！',['type2' => 1024,'msg' => "您有一个新的线上订单"]);
                        }catch (\Exception $e){}


                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'订单支付','n_content'=>'购买'.$oi_goods_name.'商品订单支付成功，等待卖家处理','n_images'=>'','n_type'=>2,'n_user_id'=>$user['user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                        try{
                            $b->jpushUser(1,$user['user_id'],'订单支付成功，等待卖家处理',json([]));

                            $b->jpushDeviceShop($info['o_shop_id'], '您有一个新的线上订单');
                        }catch (\Exception $e){}

                        if($info['o_m_user_id'] > 0){
                            Db::name('notice')->insert (['n_to'=>1,'n_title'=>'订单支付','n_content'=>'用户购买您的小店'.$oi_goods_name.'商品订单支付成功，确认收货后佣金到账','n_images'=>'','n_type'=>2,'n_user_id'=>$info['o_m_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                            try{
                                $b->jpushUser(1,$info['o_m_user_id'],'您的小店订单支付成功，确认收货后佣金到账',json([]));
                            }catch (\Exception $e){}
                        }

                        break;
                    case 'payMoneyTeam':
                        $info = Db::name('m_order')->where('mo_order_num', $num)->find();
                        $one_good = Db::name('product')->where('p_id', $info['mo_p_id'])->find();
                        $oi_goods_name = $info['mo_goods_name'];
                        $haveUsersData = Db::name('m_order')
                            ->where('mo_status', 1)
                            ->where('mo_pay_status', 2)
                            ->where('mo_store_uid', $info['mo_store_uid'])
                            ->where('mo_p_id', $info['mo_p_id'])
                            ->select();
                        $haveUsersData[] = $info;
                        $haveUsers = count($haveUsersData);
                        $o_status = in_array($info['mo_cate'], [1, 3]) ? 2 : 10;
                        $mo_update = [
                            'mo_pay_status' => 2,
                            'mo_pay_money' => $getInfo['total_fee'] / 100,
                            'mo_third_order_num' => $getInfo['transaction_id'],
                            'mo_team_money' => $one_good['p_m_team_all_money'],
                            'mo_o_status' => $o_status,
                            'mo_status' => 1,
                        ];
                        if ($info['mo_store_uid']) {
                            $leftData = Db::name('m_goods')
                                ->where('good_p_id', $info['mo_p_id'])
                                ->where('good_user_id', $info['mo_store_uid'])
                                ->field('good_team_count,good_team_status')
                                ->find();
                            $left = $leftData['good_team_count'];
                            $reatart_status = $leftData['good_team_status'];
                            $mo_update['mo_team_count'] = $info['mo_p_id'] . $info['mo_store_uid'] . $left;
                        } else {
                            $mo_update['mo_team_count'] = $info['mo_p_id'] . 0 . $one_good['p_m_team_count'];
                            $reatart_status = $one_good['p_m_team_can_status'];
                        }
                        //-------------------------------------------------------------------------------------------
                        Db::name('notice')->insert(['n_to' => 1, 'n_title' => '订单支付', 'n_content' => '购买' . $oi_goods_name . '商品订单参团成功，等待开奖', 'n_images' => '', 'n_type' => 2, 'n_user_id' => $info['mo_user_id'], 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
                        try {
                            $b->jpushUser(1, $info['mo_user_id'], '订单支付成功，您已成功参团，等待开奖', json([]));
                        } catch (\Exception $e) {
                        }
                        //-------------------------------------------------------------------------------------------
                        if ($haveUsers == $one_good['p_m_team_nums']) { //开奖啦
                            //1、先把自己的改为已开奖
                            $mo_update['mo_status'] = 2;
                            //2、再把其他的改为已开奖(挪到第4一起了)
                            //3、期数加1，更改开始的状态和时间
                            if ($info['mo_store_uid']) {
                                Db::name('m_goods')
                                    ->where('good_p_id', $info['mo_p_id'])
                                    ->where('good_user_id', $info['mo_store_uid'])
                                    ->inc('good_team_count')
                                    ->update(['good_team_status' => 1]);
                            } else {
                                Db::name('product')->where('p_id', $info['mo_p_id'])
                                    ->inc('p_m_team_count')
                                    ->update(['p_m_team_can_status' => 1]);
                            }
                            //4、开奖(先找出所有的，再排除中过的，最后统一改)
                            $joinUsers = Db::name('m_order')
                                ->where('mo_pay_status', 2)
                                ->where('mo_store_uid', $info['mo_store_uid'])
                                ->where('mo_p_id', $info['mo_p_id'])
                                ->where('mo_team_count', $mo_update['mo_team_count'])
                                ->column('mo_user_id');
                            $joinUsers[] = $info['mo_user_id'];
                            $todayPriceUser = Db::name('m_order')
                                ->where('mo_get_user_id', '>', 0)
                                ->whereTime('mo_time', 'today')
                                ->group('mo_get_user_id')
                                ->column('mo_get_user_id');
                            $lastUsers = array_diff($joinUsers, $todayPriceUser);
                            if (empty($lastUsers)) {
                                $lastUsers = $joinUsers;
                            }
                            $randUser = rand(0, count($lastUsers) - 1);
                            $get_user_id = $lastUsers[$randUser];
                            $mo_update['mo_get_user_id'] = $get_user_id;
                            Db::name('m_order')
                                ->where('mo_pay_status', 2)
                                ->where('mo_store_uid', $info['mo_store_uid'])
                                ->where('mo_p_id', $info['mo_p_id'])
                                ->where('mo_team_count', $mo_update['mo_team_count'])
                                ->update(['mo_status' => 2, 'mo_get_user_id' => $get_user_id, 'mo_team_money' => $one_good['p_m_team_all_money']]);
                            if($get_user_id == $info['mo_user_id']){
                                $getOrderUser = $info;
                                $getOrderUser['mo_third_order_num'] = $getInfo['transaction_id'];
                                $getOrderUser['mo_team_money'] = $one_good['p_m_team_all_money'];
                            }else{
                                $getOrderUser = Db::name('m_order')
                                    ->where('mo_store_uid', $info['mo_store_uid'])
                                    ->where('mo_p_id', $info['mo_p_id'])
                                    ->where('mo_team_count', $mo_update['mo_team_count'])
                                    ->where('mo_user_id', $get_user_id)
                                    ->order('mo_time desc')
                                    ->find();
                            }
                            //5、入订单表：
                            $j_param1 = [
                                'o_type' => 2,
                                'o_user_id' => $get_user_id,
                                'o_order_num' => $getOrderUser['mo_order_num'],
                                'o_third_order_num' => $getOrderUser['mo_third_order_num'],
                                'o_money' => $getOrderUser['mo_money'],
                                'o_m_money' => $getOrderUser['mo_team_money'],
                                'o_status' => $o_status,
                                'o_pay_type' => $getOrderUser['mo_pay_type'],
                                'o_pay_status' => 2,
                                'o_shop_id' => $getOrderUser['mo_shop_id'],
                                'o_shop_name' => $getOrderUser['mo_shop_name'],
                                'o_cate' => $getOrderUser['mo_cate'],
                                'o_postage' => $getOrderUser['mo_postage'],
                                'o_qrcode' => $getOrderUser['mo_qrcode'],
                                'o_name' => $getOrderUser['mo_name'],
                                'o_phone' => $getOrderUser['mo_phone'],
                                'o_address' => $getOrderUser['mo_address'],
                                'o_m_type' => 3,
                                'o_m_user_id' => $getOrderUser['mo_store_uid'],
                                'o_m_team_uids' => ',' . implode($joinUsers, ',') . ',',
                                'o_add_time' => $getOrderUser['mo_time'],
                            ];
                            $j_get_id1 = Db::name('order')->insertGetId($j_param1);
                            $j_info_param1 = [
                                'oi_order_id' => $j_get_id1,
                                'oi_goods_id' => $getOrderUser['mo_p_id'],
                                'oi_goods_name' => $getOrderUser['mo_goods_name'],
                                'oi_goods_image' => $getOrderUser['mo_goods_image'],
                                'oi_goods_price' => $getOrderUser['mo_goods_price'],
                                'oi_goods_model' => $getOrderUser['mo_goods_model'], //规格名字
                                'oi_num' => 1,
                                'oi_total_price' => $getOrderUser['mo_goods_price'],
                                'oi_total_jifen' => 0
                            ];
                            Db::name('order_info')->insert($j_info_param1);
                            //6、分佣：
                            //-----------------------------分佣 start -----------------------------------------
                            $today = date('Y-m-d H:i:s');
                            $one_fen = [];
                            $one_fen[] = [
                                'record_order_number' => $getOrderUser['mo_order_num'],
                                'record_user_id' => 0,
                                'record_from_type' => 5,
                                'record_payment_type' => $getOrderUser['mo_pay_type'],
                                'record_status' => 2,
//                                'record_get_type' => 1,
                                'record_jifen' => 0,
                                'record_money' => $one_good['p_m_team_system'],
                                'record_add_time' => $today,
                                'record_sure_time' => $today,
                                'record_type' => 2
                            ];
                            $one_fen[] = [
                                'record_order_number' => $getOrderUser['mo_order_num'],
                                'record_user_id' => $get_user_id,
                                'record_from_type' => 8,
                                'record_payment_type' => $getOrderUser['mo_pay_type'],
                                'record_status' => 2,
//                                'record_get_type' => 1,
                                'record_jifen' => $one_good['p_m_team_join_jifen'],
                                'record_money' => $one_good['p_m_team_join_money'],
                                'record_add_time' => $today,
                                'record_sure_time' => $today,
                                'record_type' => 2
                            ];
                            $captain_pay_type = 0;
                            foreach ($haveUsersData as $k => $v) {
                                if ($v['mo_user_id'] == $info['mo_store_uid']) {
                                    $captain_pay_type = $v['mo_pay_type'];
                                }
                                $now_v = [
                                    'record_order_number' => $getOrderUser['mo_order_num'],
                                    'record_user_id' => $v['mo_user_id'],
                                    'record_from_type' => 8,
                                    'record_payment_type' => $v['mo_pay_type'],
                                    'record_status' => 2,
//                                    'record_get_type' => 1,
                                    'record_jifen' => 0,
                                    'record_money' => $one_good['p_m_team_join_money'],
                                    'record_add_time' => $today,
                                    'record_sure_time' => $today,
                                    'record_type' => 2
                                ];
                                if ($v['mo_user_id'] == $get_user_id) {
                                    $now_v['record_from_type'] = 2;
//                                    $now_v['record_get_type'] = 2;
                                    $now_v['record_jifen'] = $one_good['p_give'];
                                    $now_v['record_money'] = 0;
                                    $one_fen[] = $now_v;
                                    Db::name('win_info')->insert(['w_info'=>'恭喜拼中'.$oi_goods_name.'商品','w_user_id'=>$get_user_id,'w_type'=>2,'w_add_time'=>date('Y-m-d H:i:s')]);
                                    Db::name('notice')->insert(['n_to' => 1, 'n_title' => '团团赚开奖', 'n_content' => '购买' . $oi_goods_name . '商品订单参团已开奖，恭喜您，中奖了!并获得推广奖励¥'.$one_good['p_m_team_join_money'].'元，'.$one_good['p_m_team_join_jifen'].'积分', 'n_images' => '', 'n_type' => 5, 'n_user_id' => $v['mo_user_id'], 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
                                    try {
                                        $b->jpushUser(1, $get_user_id, '团团赚已开奖，恭喜您中奖~', json([]));
                                    } catch (\Exception $e) {
                                    }
                                } else {
//                                    $now_v['record_get_type'] = 2;
                                    $now_v['record_jifen'] = $one_good['p_m_team_join_jifen'];
                                    $one_fen[] = $now_v;

                                    Db::name('notice')->insert(['n_to' => 1, 'n_title' => '团团赚开奖', 'n_content' => '购买' . $oi_goods_name . '商品订单参团已开奖，您未中奖，支付金额将原路返回，并获得推广奖励¥'.$now_v['record_money'].'元，'.$now_v['record_jifen'].'积分', 'n_images' => '', 'n_type' => 5, 'n_user_id' => $v['mo_user_id'], 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
                                    try {
                                        $b->jpushUser(1, $v['mo_user_id'], '团团赚已开奖，您未中奖~', json([]));
                                    } catch (\Exception $e) {
                                    }
                                }
                            }
                            if ($info['mo_store_uid']) {
                                $one_fen[] = [
                                    'record_order_number' => $getOrderUser['mo_order_num'],
                                    'record_user_id' => $info['mo_store_uid'],
                                    'record_from_type' => 7,
                                    'record_payment_type' => $captain_pay_type,
                                    'record_status' => 2,
//                                    'record_get_type' => 1,
                                    'record_jifen' => $one_good['p_m_team_leader_jifen'],
                                    'record_money' => $one_good['p_m_team_leader_money'],
                                    'record_add_time' => $today,
                                    'record_sure_time' => $today,
                                    'record_type' => 2
                                ];
                            } else {
                                $one_fen[] = [
                                    'record_order_number' => $getOrderUser['mo_order_num'],
                                    'record_user_id' => 0,
                                    'record_from_type' => 6,
                                    'record_payment_type' => 0,
                                    'record_status' => 2,
//                                    'record_get_type' => 1,
                                    'record_jifen' => $one_good['p_m_team_leader_jifen'],
                                    'record_money' => $one_good['p_m_team_leader_money'],
                                    'record_add_time' => $today,
                                    'record_sure_time' => $today,
                                    'record_type' => 2
                                ];
                            }
                            //立即到账
                            if ($getOrderUser['mo_store_uid'] && $getOrderUser['mo_store_uid'] > 0) {
                                $qu = Db::name('u_user')->where('user_id',$getOrderUser['mo_store_uid'])->value('user_area');
                            }else{
                                $qu = Db::name('shop')->where('shop_id',$getOrderUser['mo_shop_id'])->value('shop_qu_id');
                            }
                            $quname = Db::name('area')->where('district_id', $qu)->value('district');
                            $cc = [
                                '3' => '用户购买' . $one_good['p_name'] . '商品返佣',
                                '4' => '用户购买' . $one_good['p_name'] . '商品返佣',
                                '7' => $one_good['p_name'] . '商品团团赚团长奖励',
                                '8' => $one_good['p_name'] . '商品参与团团赚奖励',
                            ];
                            foreach ($one_fen as $fen_k => $fen_v) {
                                if(in_array($fen_v['record_from_type'],[3,4,7,8])) {
                                    if ($fen_v['record_money'] > 0) {
                                        Db::name('u_user')->where('user_id', $fen_v['record_user_id'])->setInc('user_m_pool_money', $fen_v['record_money']);
                                    }
                                    if ($fen_v['record_jifen'] > 0) {
                                        $this->jifenFlow($fen_v['record_jifen'], $qu, $fen_v['record_user_id'], 'poolFenYong');
                                        Db::name('jifen_consume')->insert(['consume_content' => $cc[$fen_v['record_from_type']] . $fen_v['record_jifen'] . "积分({$quname})", 'consume_user_id' => $fen_v['record_user_id'], 'consume_add_time' => date('Y-m-d H:i:s')]);
                                    }
                                    //推送待定
//                                    Db::name('jifen_consume')->insert(['consume_content'=>'购买产品池'.$give['p_name'].'商品赠送'.$give['p_give'] * $ss['oi_num'].'积分','consume_user_id'=>$order['o_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
//                                    Db::name('notice')->insert (['n_to'=>1,'n_title'=>'购买商品','n_content'=>'购买'.$give['p_name'].'商品赠送'.$give['p_give'] * $ss['oi_num'].'积分','n_images'=>'','n_type'=>2,'n_user_id'=>$order['o_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
//                                    $this->jpushUser(1,$order['o_user_id'],'购买'.$give['p_name'].'商品赠送'.$give['p_give'] * $ss['oi_num'].'积分',json([]));
                                }
                            }
                            Db::name('m_record')->insertAll($one_fen);
                            //-----------------------------分佣 end  ------------------------------------------
                            //6、其他设置
//                            if(!$one_good['p_give']) $one_good['p_give'] = 0;
//                            $red_yajin_jian = $one_good['p_give'] * $red_rat;
                            Db::name('shop')->where('shop_id', $info['mo_shop_id'])->setInc('shop_balance_yet', $getOrderUser['mo_money']-$getOrderUser['mo_team_money']);
                            Db::name('notice')->insert(['n_to' => 2, 'n_title' => '订单消息', 'n_content' => '您有新的订单！', 'n_images' => '', 'n_type' => 2, 'n_user_id' => $info['mo_shop_id'], 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
                            try {
                                $b->jpushShop(1, $info['mo_shop_id'], '您有新的订单！', ['type2' => 1024, 'msg' => "您有一个新的线上订单"]);
                            } catch (\Exception $e) {
                            }

                        } else {
                            //如果是第一个付款的，重启状态和时间
                            if ($info['mo_store_uid']) {
                                if ($reatart_status == 1) {
                                    Db::name('m_goods')
                                        ->where('good_p_id', $info['mo_p_id'])
                                        ->where('good_user_id', $info['mo_store_uid'])
                                        ->update([
                                            'good_team_status' => 2,
                                            'good_team_start_time' => date('Y-m-d H:i:s'),
                                            'good_team_end_time' => date('Y-m-d H:i:s', strtotime("+{$one_good['p_m_team_hours']} hours"))
                                        ]);
                                    Db::name('notice')->insert(['n_to' => 1, 'n_title' => '开团消息', 'n_content' => '您小店的'.$oi_goods_name . '商品已开团，请知悉', 'n_images' => '', 'n_type' => 2, 'n_user_id' => $info['mo_store_uid'], 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
                                    try {
                                        $b->jpushUser(1, $info['mo_store_uid'], '您小店的'.$oi_goods_name . '商品已开团', json([]));
                                    } catch (\Exception $e) {
                                    }
                                }

                            } else {
                                if ($reatart_status == 1) {
                                    Db::name('product')->where('p_id', $info['mo_p_id'])
                                        ->update([
                                            'p_m_team_can_status' => 2,
                                            'p_m_team_can_starttime' => date('Y-m-d H:i:s'),
                                            'p_m_team_can_endtime' => date('Y-m-d H:i:s', strtotime("+{$one_good['p_m_team_hours']} hours"))
                                        ]);
                                }
                            }
                        }
//

                        Db::name('m_order')->where('mo_order_num', $info['mo_order_num'])->update($mo_update);
                        if ($info['mo_goods_model']) {
                            //不是id......
//                            Db::name('product_model')->where('m_id',$info['mo_goods_model'])->setDec ('m_num',1);
                        } else {
                            Db::name('product')->where('p_id', $info['mo_p_id'])->setDec('p_stock_num', 1);
                        }
                        Db::name('product')->where('p_id', $info['mo_p_id'])->setInc('p_sell_yet', 1);
                        break;
                    // 合伙人
                        case 'upPartner':
                            if ($info['o_pay_status'] != 2) {
                                // 付款成功添加合伙人信息
                                $temp['par_user_id'] = $info['o_user_id'];
                                $par_user_info  = DB::name('u_user')
                                                ->where(['user_id'=>$info['o_user_id']])
                                                ->field('user_username,user_phone,user_area,user_recommend')
                                                ->find();
                                $temp['par_user_username']  = $par_user_info['user_username'];
                                $temp['par_user_phone']     = $par_user_info['user_phone'];
                                $temp['par_qu_id']          = $par_user_info['user_area'];
                                $temp['par_add_time']       = date('Y-m-d H:i:s',time());
                                $temp['par_class_id']       = $info['o_class_id'];
                                $partner_class = DB::name('partner_class')
                                                ->where(['class_id'=>$info['o_class_id']])
                                                ->field('class_level,class_name,class_jifen,class_tui_jifen,class_agent_money,class_head_money,class_tui_money,class_fans_days')
                                                ->find();
                                $temp['par_class_level'] = $partner_class['class_level'];
                                // 如果是城市合伙人，需要后台代理商绑定
                                if ($partner_class['class_level'] != 3) {
                                    $temp['par_status'] = 2;
                                }else{
                                    $temp['par_status'] = 1;
                                }
                                // 是否是推荐人推荐
                                if (!empty($par_user_info['user_recommend'])) {
                                    $par_parent_id = DB::name('partner')
                                                    ->where(['par_user_id'=>$par_user_info['user_recommend'],'par_cancel'=>0])
                                                    ->value('par_id');
                                    if (!empty($par_parent_id)) {
                                        $temp['par_parent_id'] = $par_parent_id;
                                    }
                                }
                                // 升级合伙人
                                if ($info['o_partner_up'] == 1) {
                                    $old = DB::name('partner')
                                        ->where(['par_user_id'=>$info['o_user_id'],'par_cancel'=>0])
                                        ->find();
                                    $old_id = $old['par_id'];
                                    //往前推时间，减去已使用时间
                                    $date1 = date("Y-m-d",strtotime ($old['par_add_time']));
                                    $date2 = date ("Y-m-d");
                                    $diff = (strtotime ($date2) - strtotime($date1)) / (60 * 60 * 24);
                                    
                                    // 剩余粉丝天数计算
                                    $oldFansDays = DB::name('partner_class')->where(['class_id'=>$old['par_class_id']])->value('class_fans_days');
                                    $newFansDays = $partner_class['class_fans_days'];
                                    if ($diff > $oldFansDays) {
                                        $diff = $newFansDays - $oldFansDays;
                                        $temp['par_add_time'] = date("Y-m-d H:i:s",strtotime("+{$diff} day",strtotime ($temp['par_add_time'])));
                                    } else {
                                        // 还是原来的日期
                                        $temp['par_add_time'] = $old['par_add_time'];
                                    }

                                    $old_partner    = DB::name('partner')
                                                    ->where(['par_user_id'=>$info['o_user_id'],'par_cancel'=>0])
                                                    ->update(['par_cancel'=>1]);
                                    if (!empty($old_partner)) {
                                        $temp['par_up'] = 1;
                                    }
                                }
                                $temp['par_cancel'] = 0;
                                $partner_add = DB::name('partner')->insertGetId($temp);
                                // 判断合伙人的区代理是否存在，不存在积分由琅琊区1134出
                                $is_qu = DB::name('admin')->where('area',$temp['par_qu_id'])->find();
                                if (empty($is_qu)) {
                                    $temp['par_qu_id'] = 1134;
                                }
                                if (!empty($partner_add)) {
                                    // 修改用户表用户等级/付款方式
                                    if ($temp['par_class_level'] == 1) {
                                        $user_level = 4;
                                    }elseif ($temp['par_class_level'] == 2) {
                                        $user_level = 3;
                                    }
                                    // 修改用户信息
                                    if (!empty($user_level)) {
                                        DB::name('u_user')->where(['user_id'=>$info['o_user_id']])->update(['user_level'=>$user_level,'user_partner_type'=>$info['o_pay_type']]);
                                    }
                                    // 如果是升级用户，修改所有的该用直接下级的par_parent_id
                                    if ($info['o_partner_up'] == 1) {
                                        DB::name('partner')->where(['par_parent_id'=>$old_id])->update(['par_parent_id'=>$partner_add]);
                                    }
                                    // 付款成功奖励积分
                                    $integral = $info['o_money'];// 奖励用户支付钱的积分数
                                    Db::name('admin')->where('area',$temp['par_qu_id'])->setDec('integral',$integral);//代理送出积分
                                    $this->jifenFlow($integral,$temp['par_qu_id'],$info['o_user_id'],"partner");
                                    Db::name('jifen_consume')->insert(['consume_content'=>'您升级为'.$partner_class['class_name'].'获得'.$integral.'积分','consume_user_id'=>$info['o_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                                    Db::name('notice')->insert (['n_to'=>1,'n_title'=>'成为合伙人','n_content'=>'您升级为'.$partner_class['class_name'].'支付金额'.$info['o_money'].'元','n_images'=>'','n_type'=>3,'n_user_id'=>$info['o_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                                    $this->jpushUser(1,$info['o_user_id'],'您升级为'.$partner_class['class_name'].'支付金额'.$info['o_money'].'元',json([]));
                                    // 推荐人奖励
                                    if (!empty($temp['par_parent_id'])) {
                                        $parent_partner = DB::name('partner')
                                                        ->where(['par_id'=>$temp['par_parent_id']])
                                                        ->find();
                                        // 判断合伙人的区代理是否存在，不存在积分由琅琊区1134出
                                        $is_parent_qu = DB::name('admin')->where('area',$parent_partner['par_qu_id'])->find();
                                        if (empty($is_qu)) {
                                            $parent_partner['par_qu_id'] = 1134;
                                        }
                                        // 如果是升级合伙人，推荐人奖励要减掉原来的推荐奖励
                                        if ($info['o_partner_up'] == 1) {
                                            $form_tui = DB::name('partner_invite')
                                                        ->where(['inv_be_userid'=>$info['o_user_id'],'inv_type'=>2,'inv_level'=>1,'inv_user_id'=>$parent_partner['par_user_id']])
                                                        ->field('inv_id,inv_integral,inv_money')
                                                        ->select();
                                            $form_jifen = 0;
                                            $form_money = 0;
                                            foreach ($form_tui as $key => $vo) {
                                                $form_jifen += $vo['inv_integral'];
                                                $form_money += $vo['inv_money'];
                                            }
                                            $partner_class['class_tui_jifen'] = $partner_class['class_tui_jifen'] - $form_jifen;
                                        }
                                        // 积分奖励
                                        Db::name('admin')->where('area',$parent_partner['par_qu_id'])->setDec('integral',$partner_class['class_tui_jifen']);//代理送出积分
                                        $this->jifenFlow($partner_class['class_tui_jifen'],$parent_partner['par_qu_id'],$parent_partner['par_user_id'],"parentPartner");
                                        // 邀请合伙人获得的积分奖励
                                        DB::name('u_user')->where(['user_id'=>$parent_partner['par_user_id']])->setInc('user_par_integral',$partner_class['class_tui_jifen']);
                                        // 添加获得积分奖励记录
                                        $arr = [
                                                'inv_user_id'   => $parent_partner['par_user_id'],
                                                'inv_par_id'    => $parent_partner['par_id'],
                                                'inv_integral'  => $partner_class['class_tui_jifen'],
                                                'inv_level'     => 1,
                                                'inv_type'      => 2,
                                                'inv_be_userid' => $info['o_user_id'],
                                                'inv_add_time'  => date('Y-m-d H:i:s',time())
                                        ];
                                        DB::name('partner_invite')->insert($arr);
                                        $str1 = '';
                                        // 事业合伙人送推荐人现金
                                        if (!empty($partner_class['class_tui_money'])) {
                                            // 如果是升级合伙人，推荐人奖励要减掉原来的推荐奖励
                                            if ($info['o_partner_up'] == 1) {
                                                $partner_class['class_tui_money'] = $partner_class['class_tui_money'] - $form_money;
                                            }
                                            // 增加现金提现额度
                                            DB::name('u_user')->where(['user_id'=>$parent_partner['par_user_id']])->setInc('user_money_balance',$partner_class['class_tui_money']);
                                            // 记录现金收益
                                            $arr = [
                                                'inv_user_id'   => $parent_partner['par_user_id'],
                                                'inv_par_id'    => $parent_partner['par_id'],
                                                'inv_money'     => $partner_class['class_tui_money'],
                                                'inv_level'     => 1,
                                                'inv_type'      => 2,
                                                'inv_be_userid' => $info['o_user_id'],
                                                'inv_add_time'  => date('Y-m-d H:i:s',time())
                                            ];
                                            DB::name('partner_invite')->insert($arr);
                                            // 邀请合伙人获得的现金奖励
                                            DB::name('u_user')->where(['user_id'=>$parent_partner['par_user_id']])->setInc('user_par_money',$partner_class['class_tui_money']);
                                            $str1 = $partner_class['class_tui_money'].'元+';
                                        }
                                        Db::name('jifen_consume')->insert(['consume_content'=>'您邀请'.$temp['par_user_username'].'成为'.$partner_class['class_name'].'获得'.$str1.$partner_class['class_tui_jifen'].'积分奖励','consume_user_id'=>$parent_partner['par_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'推荐合伙人','n_content'=>'您邀请'.$temp['par_user_username'].'成为'.$partner_class['class_name'].'获得'.$str1.$partner_class['class_tui_jifen'].'积分奖励','n_images'=>'','n_type'=>3,'n_user_id'=>$parent_partner['par_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                                        // $this->jpushUser(1,$parent_partner['par_user_id'],'您邀请'.$temp['par_user_username'].'成为'.$partner_class['class_name'].'获得'.$str1.$partner_class['class_tui_jifen'].'积分奖励',json([]));
                                    }
                                    // 升级合伙人代理商和总部的收益要减去之前的收益
                                    $area_money = DB::name('earnings')
                                                ->where(['m_area_user'=>$info['o_user_id'],'m_area_type'=>2,'m_area'=>$temp['par_qu_id']])
                                                ->sum('m_money');
                                    $head_money = DB::name('earnings')
                                                ->where(['m_area_user'=>$info['o_user_id'],'m_area_type'=>1,'m_area'=>1])
                                                ->sum('m_money');
                                    if (!empty($area_money)) {
                                        $partner_class['class_agent_money'] = $partner_class['class_agent_money'] - $area_money;
                                    }
                                    if (!empty($head_money)) {
                                        $partner_class['class_head_money'] = $partner_class['class_head_money'] - $head_money;
                                    }
                                    // 代理商获得奖励没有代理就总部拿
                                    if (!empty($is_qu)) {
                                        DB::name('admin')->where(['area'=>$temp['par_qu_id']])->setInc('balance',$partner_class['class_agent_money']);
                                    }else{
                                        DB::name('admin')->where('id',1)->setInc('balance',$partner_class['class_agent_money']);
                                    }
                                    // 记录现金收益
                                    Db::name('earnings')->insert(['m_money'=>$partner_class['class_agent_money'],'m_area'=>$temp['par_qu_id'],'m_add_time'=>date('Y-m-d H:i:s'),'m_area_type'=>2,'m_area_user'=>$temp['par_user_id']]);
                                    // 总部获得奖励
                                    DB::name('admin')->where('id',1)->setInc('balance',$partner_class['class_head_money']);
                                    // 记录现金收益
                                    Db::name('earnings')->insert(['m_money'=>$partner_class['class_head_money'],'m_area'=>1,'m_add_time'=>date('Y-m-d H:i:s'),'m_area_type'=>1,'m_area_user'=>$temp['par_user_id']]);
                                }
                            }
                        break;
                }
                if ($getInfo['attach'] == 'upPartner') {
                    if ($info['o_pay_status'] != 2) {
                        Db::name('admin')->where('id',1)->setInc ('balance',$getInfo['total_fee']/100 );
                    }
                }else{
                    if($getInfo['attach'] != 'payMoneyOne' && $getInfo['attach'] != 'payMoneyTeam') {
                        Db::name('admin')->where('id', 1)->setInc('balance', $getInfo['total_fee'] / 100);
                    }
                }
                if($getInfo['attach'] != 'payMoney' && $getInfo['attach'] != 'payMoneyOne' && $getInfo['attach'] != 'payMoneyTeam') {
                    Db::name ('order')->where ('o_order_num' , $num)->update (['o_pay_status' => 2 , 'o_third_order_num' => $getInfo['transaction_id']]);
                }
                Db::commit ();
            }catch(\Exception $e){
                file_put_contents ( APP_PATH."api/controller/wxpay_user1_log.txt", date ( "Y-m-d H:i:s" ) . "  " . $e . "\r\n", FILE_APPEND );
                Db::rollback ();
            }
            $result = true;
        }else{
            $result = false;
        }
        ob_clean();
        if (!empty($result)) {
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        }else{
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;exit;
    }


    public function huidiao1(){
        $xml=file_get_contents('php://input');
        $getInfo=$this->toArray($xml);
        $this->write_admin_log("response: ".var_export($getInfo,true));
        $data_sign=$getInfo['sign'];
        unset($getInfo['sign']);
        $sign=$this->makeSign($getInfo);
        if ($sign===$data_sign && $getInfo['return_code']=='SUCCESS' && $getInfo['result_code']=='SUCCESS') {
            Db::startTrans ();
            try{
                $num = $getInfo['out_trade_no'];
                $money = $getInfo['total_fee']/100;
                $record = Db::name('record')->where(['record_number'=>$num])->find();
                $shop = Db::name('shop')->where(['shop_id'=>$record['record_shop_id']])->find();
                $rate = Db::name('jifen_conf')->where('conf_id',1)->value ('conf_rate');

                $time = $this->getDateBytimeDate("{$getInfo['time_end']}");
                $b = new Base();
                $money = $record['record_money'];
                $yajin = 0;
                if($record['record_give_jifen'] > 0){
                    $yajin = $record['record_give_jifen']*$rate;
//                    Db::name('shop')->where(['shop_id'=>$record['record_shop_id']])->dec('shop_integral',$record['record_give_jifen'])->dec('shop_pledge_money',$record['record_give_jifen']*$rate)->update();
                    try{
                        $b->jifenFlow($record['record_give_jifen'],$shop['shop_qu_id'],$record['record_user_id'],"QRcodePay");
                    }catch (\Exception $e){

                    }
//                    Db::name('jifen_consume')->insert(['consume_content'=>'扫码支付给“'.$shop['shop_name'].'”赠送'.$record['record_give_jifen'].'积分','consume_user_id'=>$record['record_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                    Db::name('order')->insert(['o_type'=>5,'o_order_num'=>$this->getOrderNumber (),'o_money'=>$record['record_give_jifen']*$rate,'o_jifen'=>'','o_status'=>5,'o_pay_status'=>2,'o_shop_id'=>$record['record_shop_id'],'o_add_time'=>date('Y-m-d H:i:s')]);
                    Db::name('notice')->insert (['n_to'=>1,'n_title'=>'扫码支付','n_content'=>'扫码支付赠送'.$record['record_give_jifen'].'积分','n_images'=>'','n_type'=>2,'n_user_id'=>$record['record_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                    try{
                        $this->jpushUser(1,$record['record_user_id'],'扫码支付赠送'.$record['record_give_jifen'].'积分',json([]));
                        $this->jpushShop(1,$record['record_shop_id'],"收款{$money}元",['type'=>1,'money'=>$money,'type2' => 1024,'msg' => "支分宝到账{$money}元，送出{$record['record_give_jifen']}积分"]);
                    }catch (\Exception $e){

                    }
                }else{
					try{
                        $this->jpushShop(1,$record['record_shop_id'],"收款{$money}元",['type'=>1,'money'=>$money,'type2' => 1024,'msg' => "支分宝到账{$money}元，没有送出积分"]);
                    }catch (\Exception $e){

                    }
				}
                Db::name('jifen_consume')
                    ->insert ([
                        'consume_content'=>'扫码支付给“'.$shop['shop_name'].'”'.$money.'元，赠送'.$record['record_give_jifen'].'积分',
                        'consume_user_id'=>$record['record_user_id'],
                        'consume_add_time'=>date("Y-m-d H:i:s")
                    ]);
                Db::name('record')
                    ->where(['record_id'=>$record['record_id']])
                    ->update([
                        'record_third_number' => $getInfo['transaction_id'],
                        'record_status'=>2,
                        'record_pay_time'=>$time,
                        'record_shop_balance'=>$shop['shop_balance']+$money-$yajin
                    ]);
                Db::name('shop')
                    ->where('shop_id',$shop['shop_id'])
                    ->inc ('shop_balance',$money-$yajin)->inc('shop_all_balance',$money-$yajin)->update();
                // 店铺现金成交额
                Db::name('shop')
                    ->where('shop_id',$shop['shop_id'])
                    ->setInc('shop_money_balance',$money-$yajin);
                // 店铺当日现金交易额// 定时任务，每日0点清空
                DB::name('shop')->where('shop_id',$shop['shop_id'])->setInc ('shop_today_balance',$money-$yajin);
                // 店铺现金交易1‰分红
                $shop_user_id   = DB::name('shop')
                                ->where('shop_id',$shop['shop_id'])
                                ->value('shop_user_id');
                $this->shop_profit($shop['shop_id'],$shop_user_id,$money,3);
                //-----------------------红包改状态---------------------
                if($record['record_ru_id'] > 0){
                    Db::name('m_red_user')
                        ->where('ru_id',$record['record_ru_id'])
                        ->update([
                            'ru_status' => 2
                        ]);
                }
                Db::commit ();
            }catch(\Exception $e){
                Db::rollback ();
            }
            $result = true;
        }else{
            $result = false;
        }
        ob_clean();
        if (!empty($result)) {
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        }else{
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;exit;
    }
    public function huidiaored(){
        $xml=file_get_contents('php://input');
        $getInfo=$this->toArray($xml);
        $this->write_admin_log("response: ".var_export($getInfo,true));
        $data_sign=$getInfo['sign'];
        unset($getInfo['sign']);
        $sign=$this->makeSign($getInfo);
        if ($sign===$data_sign && $getInfo['return_code']=='SUCCESS' && $getInfo['result_code']=='SUCCESS') {
            Db::startTrans ();
            try{
                $num = $getInfo['out_trade_no'];
                Db::name('m_red')
                    ->where(['red_number'=>$num])
                    ->update([
                        'red_status'=>2
                    ]);
                Db::commit ();
            }catch(\Exception $e){
                Db::rollback ();
            }
            $result = true;
        }else{
            $result = false;
        }
        ob_clean();
        if (!empty($result)) {
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        }else{
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;exit;
    }


    public function weixiReturn($total_fee, $refund_fee, $transaction_id, $out_refund_no){
        $url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
        $config_data = [
            'appid' => $this->config['APPID'],
            'mch_id' => $this->config['MCHID'],
            'nonce_str' => $this->getRandChar(32),
            'out_trade_no' => '',
            'transaction_id'=>$transaction_id,
            'out_refund_no' => $out_refund_no,
            'total_fee' => $total_fee * 100,
            'refund_fee' => $refund_fee * 100,
        ];
        $config_data['sign'] = $this->makeSign($config_data);
        $data = $this->toXml($config_data);
        $res = $this->toArray($this->httpRequest($url, $data));
        if($res['return_code'] == "SUCCESS"){
            return ['status'=>200,'msg'=>$res['return_msg']];
        }else{
            return ['status'=>100,'msg'=>$res['return_msg']];
        }
    }


    public function httpRequest($url, $postData = [])
    {
        $header[] = "Content-type: text/xml";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
        curl_setopt($ch,CURLOPT_SSLCERT,ROOT_PATH.'/public/apiclient_cert.pem');
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
        curl_setopt($ch,CURLOPT_SSLKEY,ROOT_PATH.'/public/apiclient_key.pem');
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $result = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }
        curl_close($ch);

        return $result;
    }
    

    public function makeSign($data){
        $data=array_filter($data);
        ksort($data);
        $string_a=http_build_query($data);
        $string_a=urldecode($string_a);
        $config=$this->config;
        $string_sign_temp=$string_a."&key=".$config['KEY'];
        $sign = md5($string_sign_temp);
        $result=strtoupper($sign);
        return $result;
    }


    public function toArray($xml){
        libxml_disable_entity_loader(true);
        $result= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $result;
    }
    

    public function toXml($data){
        if(!is_array($data) || count($data) <= 0){
        }
        $xml = "<xml>";
        foreach ($data as $key=>$val){
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }


    function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val))
            {
                $xml.="<".$key.">".$val."</".$key.">";

            }
            else
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
        $xml.="</xml>";
        return $xml;
    }

    public function postXmlCurl($xml,$url,$second=30)
    {
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        $data = curl_exec($ch);
        if($data)
        {
            curl_close($ch);
            return $data;
        }
        else
        {
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error"."<br>";
            echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
            curl_close($ch);
            return false;
        }
    }

    function getRandChar($length){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;

        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];
        }

        return $str;
    }

    public function getOrder($prepayId){
        $data["appid"] = $this->config["APPID"];
        $data["noncestr"] = $this->getRandChar(32);
        $data["package"] = "Sign=WXPay";
        $data["partnerid"] = $this->config['MCHID'];
        $data["prepayid"] = $prepayId;
        $data["timestamp"] = time();
        $s = $this->makeSign($data, false);
        $data["sign"] = $s;
        
        return $data;
    }
    

    public  function get_client_ip()
    {
        if ($_SERVER['REMOTE_ADDR']) {
            $cip = $_SERVER['REMOTE_ADDR'];
        } elseif (getenv("REMOTE_ADDR")) {
            $cip = getenv("REMOTE_ADDR");
        } elseif (getenv("HTTP_CLIENT_IP")) {
            $cip = getenv("HTTP_CLIENT_IP");
        } else {
            $cip = "unknown";
        }
        return $cip;
    }

    public function userTiXian($refundNo,$openid,$money,$name){
        $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
        $config_data = [
            'mch_appid' => $this->config['APPID'],
            'mchid' => $this->config['MCHID'],
            'nonce_str' => $this->getRandChar(32),
            'partner_trade_no' => $refundNo,
            'openid' => $openid,
            'check_name' => "FORCE_CHECK",
            're_user_name' => $name,
            'amount' =>  $money*100,
            'desc' => '支分宝转账',
            'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
        ];
        $sign = $this->makeSign($config_data);
        $config_data['sign'] = $sign;
        $xml = $this->toXml($config_data);
        $response = $this->httpRequest($url,$xml);
        $result = $this->toArray($response);
        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            return ['status'=>200,'msg'=>$result['payment_no']];
        }else if($result['return_code'] == 'FAIL'){
            return ['status'=>100,'msg'=>$result['return_msg']];
        }else{
            if($result['err_code'] == 'SENDNUM_LIMIT'){
                return ['status'=>100,'msg'=>'单个用户每天最多可提现3次'];
            }
            return ['status'=>100,'msg'=>$result['err_code_des']];
        }
    }
public function errorUpForError(){
        return 1;die;exit();
            Db::startTrans ();
            try{
                $num = '1111111111111111111111111111111111111111';
                $getInfo['attach'] = 'upPartner';
                $getInfo['total_fee'] = 100;
                $getInfo['transaction_id'] = '微信那边过来的单号';
                $info = Db::name('order')->where('o_order_num',$num)->find();
                switch($getInfo['attach']){
                    // 合伙人
                    case 'upPartner':
                        if ($info['o_pay_status'] != 2) {
                            // 付款成功添加合伙人信息
                            $temp['par_user_id'] = $info['o_user_id'];
                            $par_user_info  = DB::name('u_user')
                                ->where(['user_id'=>$info['o_user_id']])
                                ->field('user_username,user_phone,user_area,user_recommend')
                                ->find();
                            $temp['par_user_username']  = $par_user_info['user_username'];
                            $temp['par_user_phone']     = $par_user_info['user_phone'];
                            $temp['par_qu_id']          = $par_user_info['user_area'];
                            $temp['par_add_time']       = date('Y-m-d H:i:s',time());
                            $temp['par_class_id']       = $info['o_class_id'];
                            $partner_class = DB::name('partner_class')
                                ->where(['class_id'=>$info['o_class_id']])
                                ->field('class_level,class_name,class_jifen,class_tui_jifen,class_agent_money,class_head_money,class_tui_money,class_fans_days')
                                ->find();
                            $temp['par_class_level'] = $partner_class['class_level'];
                            // 如果是城市合伙人，需要后台代理商绑定
                            if ($partner_class['class_level'] != 3) {
                                $temp['par_status'] = 2;
                            }else{
                                $temp['par_status'] = 1;
                            }
                            // 是否是推荐人推荐
                            if (!empty($par_user_info['user_recommend'])) {
                                $par_parent_id = DB::name('partner')
                                    ->where(['par_user_id'=>$par_user_info['user_recommend'],'par_cancel'=>0])
                                    ->value('par_id');
                                if (!empty($par_parent_id)) {
                                    $temp['par_parent_id'] = $par_parent_id;
                                }
                            }
                            // 升级合伙人
                            if ($info['o_partner_up'] == 1) {
                                $old = DB::name('partner')
                                    ->where(['par_user_id'=>$info['o_user_id'],'par_cancel'=>0])
                                    ->find();
                                $old_id = $old['par_id'];
                                //往前推时间，减去已使用时间
                                $date1 = date("Y-m-d",strtotime ($old['par_add_time']));
                                $date2 = date ("Y-m-d");
                                $diff = (strtotime ($date2) - strtotime($date1)) / (60 * 60 * 24);

                                // 剩余粉丝天数计算
                                $oldFansDays = DB::name('partner_class')->where(['class_id'=>$old['par_class_id']])->value('class_fans_days');
                                $newFansDays = $partner_class['class_fans_days'];
                                if ($diff > $oldFansDays) {
                                    $diff = $newFansDays - $oldFansDays;
                                    $temp['par_add_time'] = date("Y-m-d H:i:s",strtotime("+{$diff} day",strtotime ($temp['par_add_time'])));
                                } else {
                                    // 还是原来的日期
                                    $temp['par_add_time'] = $old['par_add_time'];
                                }

                                $old_partner    = DB::name('partner')
                                    ->where(['par_user_id'=>$info['o_user_id'],'par_cancel'=>0])
                                    ->update(['par_cancel'=>1]);
                                if (!empty($old_partner)) {
                                    $temp['par_up'] = 1;
                                }
                            }
                            $temp['par_cancel'] = 0;
                            $partner_add = DB::name('partner')->insertGetId($temp);
                            // 判断合伙人的区代理是否存在，不存在积分由琅琊区1134出
                            $is_qu = DB::name('admin')->where('area',$temp['par_qu_id'])->find();
                            if (empty($is_qu)) {
                                $temp['par_qu_id'] = 1134;
                            }
                            if (!empty($partner_add)) {
                                // 修改用户表用户等级/付款方式
                                if ($temp['par_class_level'] == 1) {
                                    $user_level = 4;
                                }elseif ($temp['par_class_level'] == 2) {
                                    $user_level = 3;
                                }
                                // 修改用户信息
                                if (!empty($user_level)) {
                                    DB::name('u_user')->where(['user_id'=>$info['o_user_id']])->update(['user_level'=>$user_level,'user_partner_type'=>$info['o_pay_type']]);
                                }
                                // 如果是升级用户，修改所有的该用直接下级的par_parent_id
                                if ($info['o_partner_up'] == 1) {
                                    DB::name('partner')->where(['par_parent_id'=>$old_id])->update(['par_parent_id'=>$partner_add]);
                                }
                                // 付款成功奖励积分
                                $integral = $info['o_money'];// 奖励用户支付钱的积分数
                                Db::name('admin')->where('area',$temp['par_qu_id'])->setDec('integral',$integral);//代理送出积分
                                $this->jifenFlow($integral,$temp['par_qu_id'],$info['o_user_id'],"partner");
                                Db::name('jifen_consume')->insert(['consume_content'=>'您升级为'.$partner_class['class_name'].'获得'.$integral.'积分','consume_user_id'=>$info['o_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                                Db::name('notice')->insert (['n_to'=>1,'n_title'=>'成为合伙人','n_content'=>'您升级为'.$partner_class['class_name'].'支付金额'.$info['o_money'].'元','n_images'=>'','n_type'=>3,'n_user_id'=>$info['o_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                                $this->jpushUser(1,$info['o_user_id'],'您升级为'.$partner_class['class_name'].'支付金额'.$info['o_money'].'元',json([]));
                                // 推荐人奖励
                                if (!empty($temp['par_parent_id'])) {
                                    $parent_partner = DB::name('partner')
                                        ->where(['par_id'=>$temp['par_parent_id']])
                                        ->find();
                                    // 判断合伙人的区代理是否存在，不存在积分由琅琊区1134出
                                    $is_parent_qu = DB::name('admin')->where('area',$parent_partner['par_qu_id'])->find();
                                    if (empty($is_qu)) {
                                        $parent_partner['par_qu_id'] = 1134;
                                    }
                                    // 如果是升级合伙人，推荐人奖励要减掉原来的推荐奖励
                                    if ($info['o_partner_up'] == 1) {
                                        $form_tui = DB::name('partner_invite')
                                            ->where(['inv_be_userid'=>$info['o_user_id'],'inv_type'=>2,'inv_level'=>1,'inv_user_id'=>$parent_partner['par_user_id']])
                                            ->field('inv_id,inv_integral,inv_money')
                                            ->select();
                                        $form_jifen = 0;
                                        $form_money = 0;
                                        foreach ($form_tui as $key => $vo) {
                                            $form_jifen += $vo['inv_integral'];
                                            $form_money += $vo['inv_money'];
                                        }
                                        $partner_class['class_tui_jifen'] = $partner_class['class_tui_jifen'] - $form_jifen;
                                    }
                                    // 积分奖励
                                    Db::name('admin')->where('area',$parent_partner['par_qu_id'])->setDec('integral',$partner_class['class_tui_jifen']);//代理送出积分
                                    $this->jifenFlow($partner_class['class_tui_jifen'],$parent_partner['par_qu_id'],$parent_partner['par_user_id'],"parentPartner");
                                    // 邀请合伙人获得的积分奖励
                                    DB::name('u_user')->where(['user_id'=>$parent_partner['par_user_id']])->setInc('user_par_integral',$partner_class['class_tui_jifen']);
                                    // 添加获得积分奖励记录
                                    $arr = [
                                        'inv_user_id'   => $parent_partner['par_user_id'],
                                        'inv_par_id'    => $parent_partner['par_id'],
                                        'inv_integral'  => $partner_class['class_tui_jifen'],
                                        'inv_level'     => 1,
                                        'inv_type'      => 2,
                                        'inv_be_userid' => $info['o_user_id'],
                                        'inv_add_time'  => date('Y-m-d H:i:s',time())
                                    ];
                                    DB::name('partner_invite')->insert($arr);
                                    $str1 = '';
                                    // 事业合伙人送推荐人现金
                                    if (!empty($partner_class['class_tui_money'])) {
                                        // 如果是升级合伙人，推荐人奖励要减掉原来的推荐奖励
                                        if ($info['o_partner_up'] == 1) {
                                            $partner_class['class_tui_money'] = $partner_class['class_tui_money'] - $form_money;
                                        }
                                        // 增加现金提现额度
                                        DB::name('u_user')->where(['user_id'=>$parent_partner['par_user_id']])->setInc('user_money_balance',$partner_class['class_tui_money']);
                                        // 记录现金收益
                                        $arr = [
                                            'inv_user_id'   => $parent_partner['par_user_id'],
                                            'inv_par_id'    => $parent_partner['par_id'],
                                            'inv_money'     => $partner_class['class_tui_money'],
                                            'inv_level'     => 1,
                                            'inv_type'      => 2,
                                            'inv_be_userid' => $info['o_user_id'],
                                            'inv_add_time'  => date('Y-m-d H:i:s',time())
                                        ];
                                        DB::name('partner_invite')->insert($arr);
                                        // 邀请合伙人获得的现金奖励
                                        DB::name('u_user')->where(['user_id'=>$parent_partner['par_user_id']])->setInc('user_par_money',$partner_class['class_tui_money']);
                                        $str1 = $partner_class['class_tui_money'].'元+';
                                    }
                                    Db::name('jifen_consume')->insert(['consume_content'=>'您邀请'.$temp['par_user_username'].'成为'.$partner_class['class_name'].'获得'.$str1.$partner_class['class_tui_jifen'].'积分奖励','consume_user_id'=>$parent_partner['par_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                                    Db::name('notice')->insert (['n_to'=>1,'n_title'=>'推荐合伙人','n_content'=>'您邀请'.$temp['par_user_username'].'成为'.$partner_class['class_name'].'获得'.$str1.$partner_class['class_tui_jifen'].'积分奖励','n_images'=>'','n_type'=>3,'n_user_id'=>$parent_partner['par_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                                    // $this->jpushUser(1,$parent_partner['par_user_id'],'您邀请'.$temp['par_user_username'].'成为'.$partner_class['class_name'].'获得'.$str1.$partner_class['class_tui_jifen'].'积分奖励',json([]));
                                }
                                // 升级合伙人代理商和总部的收益要减去之前的收益
                                $area_money = DB::name('earnings')
                                    ->where(['m_area_user'=>$info['o_user_id'],'m_area_type'=>2,'m_area'=>$temp['par_qu_id']])
                                    ->sum('m_money');
                                $head_money = DB::name('earnings')
                                    ->where(['m_area_user'=>$info['o_user_id'],'m_area_type'=>1,'m_area'=>1])
                                    ->sum('m_money');
                                if (!empty($area_money)) {
                                    $partner_class['class_agent_money'] = $partner_class['class_agent_money'] - $area_money;
                                }
                                if (!empty($head_money)) {
                                    $partner_class['class_head_money'] = $partner_class['class_head_money'] - $head_money;
                                }
                                // 代理商获得奖励没有代理就总部拿
                                if (!empty($is_qu)) {
                                    DB::name('admin')->where(['area'=>$temp['par_qu_id']])->setInc('balance',$partner_class['class_agent_money']);
                                }else{
                                    DB::name('admin')->where('id',1)->setInc('balance',$partner_class['class_agent_money']);
                                }
                                // 记录现金收益
                                Db::name('earnings')->insert(['m_money'=>$partner_class['class_agent_money'],'m_area'=>$temp['par_qu_id'],'m_add_time'=>date('Y-m-d H:i:s'),'m_area_type'=>2,'m_area_user'=>$temp['par_user_id']]);
                                // 总部获得奖励
                                DB::name('admin')->where('id',1)->setInc('balance',$partner_class['class_head_money']);
                                // 记录现金收益
                                Db::name('earnings')->insert(['m_money'=>$partner_class['class_head_money'],'m_area'=>1,'m_add_time'=>date('Y-m-d H:i:s'),'m_area_type'=>1,'m_area_user'=>$temp['par_user_id']]);
                            }
                        }
                        break;
                }
                Db::name('admin')->where('id',1)->setInc ('balance',$getInfo['total_fee']/100 );
                Db::name ('order')->where ('o_order_num' , $num)->update (['o_pay_status' => 2 , 'o_third_order_num' => $getInfo['transaction_id']]);

                Db::commit ();
            }catch(\Exception $e){
                file_put_contents ( APP_PATH."api/controller/wxpay_user1_log.txt", date ( "Y-m-d H:i:s" ) . "  " . $e . "\r\n", FILE_APPEND );
                Db::rollback ();
            }
            $result = true;
        ob_clean();
       exit;
    }
}